package com.yc.taixin.controller;

import com.yc.taixin.model.TSUser;
import com.yc.taixin.model.resultVo.AjaxJson;
import com.yc.taixin.model.resultVo.UsersVO;
import com.yc.taixin.service.impl.UserServiceImpl;
import com.yc.taixin.service.impl.YuyueServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户模块
 * 注释:view层不应该有太复杂的逻辑
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserServiceImpl userService;
	@Autowired
	private YuyueServiceImpl yuyueService;

	@RequestMapping(value = "/login")
	public Object login(TSUser user) {
		try {
			if (user != null && user.getUsername() != null) {
				TSUser userData = userService.queryUsernameIsExist(user.getUsername());
				if (userData != null && user.getPassword().equals(userData.getPassword())) {
					request.getSession().removeAttribute("user");
					UsersVO usersVO = new UsersVO();
					BeanUtils.copyProperties(userData, usersVO);
					request.getSession().setAttribute("user", usersVO);
					Map<String, Object> map = new HashMap<String, Object>();
					//设置用户预约成功数
					map.put("userId", userData.getId());
					request.getSession().setAttribute("yuyueCount", yuyueService.countSuccess(map));
					return AjaxJson.build(200, "登录成功，3秒后自动为您跳转..", "/yuyue/list");
				} else {
					return AjaxJson.errorMsg("账号或密码错误");
				}
			}
			return new ModelAndView("user/login");
		} catch (BeansException e) {
			e.printStackTrace();
			return AjaxJson.errorMsg("账号或密码错误,请重试");
		}

	}

	@RequestMapping(value = "/regist")
	public Object regist(TSUser user, String action) {
		try {
			if (StringUtils.isNotBlank(action)) {
				TSUser userData = userService.queryUsernameIsExist(user.getUsername());//后期优化
				if (userData != null) {
					return AjaxJson.errorMsg("手机号已经注册过,请重新输入");
				}
				userService.update(user);
				return AjaxJson.build(200, "恭喜你,[+"+user.getUsername()+"+]注册成功!将自动跳转到登录界面", "/user/login");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxJson.errorMsg("参数错误,请重试");
		}
		return new ModelAndView("user/regist");
	}


}
